﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using System.Collections;
using System.Data;

namespace AgileShare.Framework.Library.Helpers
{
    /// <summary>
    /// SharePoint Survey问卷调查帮助类
    /// </summary>
    public class SPSurveyHepler
    {

        /// <summary>
        /// 获取Survery列表
        /// </summary>
        /// <param name="web"></param>
        /// <param name="listName"></param>
        /// <returns></returns>
        public static SPList GetSurveyList(SPWeb web, string listName)
        {
            SPList list = null;
            SPVerificationHelper.VerifyObjectArgument(web, "web");
            SPVerificationHelper.VerifyStringArgument(listName, "listName");
            if (web.ListExists(listName))
            {
                list = web.Lists.TryGetList(listName);
            }
            return list;
        }

        /// <summary>
        /// 获取Survery列表
        /// </summary>
        /// <param name="web"></param>
        /// <param name="guid"></param>
        /// <returns></returns>
        public static SPList GetSurveyList(SPWeb web, Guid guid) {
            SPList list = null;
            SPVerificationHelper.VerifyObjectArgument(web, "web");
            SPVerificationHelper.VerifyObjectArgument(guid, "guid");
            list = web.Lists[guid];
            return list;
        }

        /// <summary>
        /// 获取原始调查结果数据
        /// </summary>
        /// <param name="ListGuid">List Guid</param>
        /// <param name="Questions">调查问题列表</param>
        /// <param name="VoteUsers">投票人列表</param>
        /// <returns></returns>
        public static List<SurveyResult> GetSurveyResultData(Guid ListGuid,
                                                         out HashSet<string> Questions,
                                                         out Dictionary<string, string> VoteUsers,
                                                         out SPList list
            )
        {

            List<SurveyResult> ResultList = new List<SurveyResult>();
            SPWeb web = SPContext.Current.Web;
            Questions = new HashSet<string>();
            VoteUsers = new Dictionary<string, string>();
            list = null;

            var myList = GetSurveyList(web, ListGuid);

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                web.AllowUnsafeUpdates = true;
                myList.ShowUser = true;
                myList.Update();
            });

            try
            {
                if (myList != null)
                {
                    list = myList;
                    foreach (SPField fi in myList.Fields)
                    {
                        if (fi.CanBeDeleted)
                        {
                            string prefix = myList.AllowMultiResponses ? ";#" : "";
                            #region 类型处理
                            switch (fi.Type)
                            {
                                case SPFieldType.AllDayEvent:
                                    break;
                                case SPFieldType.Attachments:
                                    break;
                                case SPFieldType.Boolean:
                                    break;
                                case SPFieldType.Calculated:
                                    break;
                                case SPFieldType.Choice:
                                    SPFieldChoice choiceField;
                                    choiceField = (SPFieldChoice)fi;
                                    //foreach (string choiceName in choiceField.Choices)
                                    //{
                                    //    //Console.WriteLine(choiceName);
                                    //}
                                    break;
                                case SPFieldType.Computed:
                                    break;
                                case SPFieldType.ContentTypeId:
                                    break;
                                case SPFieldType.Counter:
                                    break;
                                case SPFieldType.CrossProjectLink:
                                    break;
                                case SPFieldType.Currency:
                                    break;
                                case SPFieldType.DateTime:
                                    break;
                                case SPFieldType.Error:
                                    break;
                                case SPFieldType.File:
                                    break;
                                case SPFieldType.GridChoice:
                                    break;
                                case SPFieldType.Guid:
                                    break;
                                case SPFieldType.Integer:
                                    break;
                                case SPFieldType.Invalid:
                                    break;
                                case SPFieldType.Lookup:
                                    break;
                                case SPFieldType.MaxItems:
                                    break;
                                case SPFieldType.ModStat:
                                    break;
                                case SPFieldType.MultiChoice:
                                    prefix = "";
                                    SPFieldMultiChoice MchoiceField;
                                    MchoiceField = (SPFieldMultiChoice)fi;
                                    //foreach (string choiceName in MchoiceField.Choices)
                                    //{
                                    //    //Console.WriteLine(choiceName);
                                    //}
                                    break;
                                case SPFieldType.Note:
                                    break;
                                case SPFieldType.Number:
                                    break;
                                case SPFieldType.PageSeparator:
                                    break;
                                case SPFieldType.Recurrence:
                                    break;
                                case SPFieldType.Text:
                                    break;
                                case SPFieldType.ThreadIndex:
                                    break;
                                case SPFieldType.Threading:
                                    break;
                                case SPFieldType.URL:
                                    break;
                                case SPFieldType.User:
                                    break;
                                case SPFieldType.WorkflowEventType:
                                    break;
                                case SPFieldType.WorkflowStatus:
                                    break;
                                default:
                                    break;
                            }
                            #endregion
                            foreach (SPListItem li in myList.Items)
                            {
                                if (li["Author"] != null && li[fi.Title] != null)
                                {
                                    var UserSaml = li["Author"].ToString();
                                    //用户类型转换
                                    SPFieldUserValue curUser = new SPFieldUserValue(SPContext.Current.Web, UserSaml);

                                    //获取问题列表
                                    if (!Questions.Contains(fi.Title))
                                    {
                                        Questions.Add(fi.Title);
                                    }
                                    //获取投票人列表
                                    if (!VoteUsers.ContainsKey(UserSaml))
                                    {
                                        VoteUsers.Add(UserSaml, curUser.User.Name);
                                    }
                                    SurveyResult result = new SurveyResult();
                                    result.ListTitle = myList.Title;
                                    result.UserName = li["Author"].ToString();
                                    result.Answer = !string.IsNullOrEmpty(li[fi.Title].ToString()) ? li[fi.Title].ToString().NoHtml() : "" + prefix;
                                    result.Question = fi.Title;
                                    result.ModifyData = li["Modified"].ToString();
                                    result.Status = li["Completed"].ToString();
                                    var userinfo = SPUserProfileHepler.GetUserProfile(curUser.User.LoginName);
                                    if (userinfo != null)
                                    {
                                        var dept = userinfo.GetUserPropertyByName("Department");
                                        result.Department = dept != null ? dept.ToString() : "";

                                        var company = userinfo.GetUserPropertyByName("Company");
                                        result.Company = company != null ? company.ToString() : "";
                                    }
                                    ResultList.Add(result);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    web.AllowUnsafeUpdates = true;
                    myList.ShowUser = false;
                    myList.Update();
                });
            }     
            return ResultList;
        }


        /// <summary>
        /// 获取所有问题
        /// </summary>
        /// <param name="ListGuid">List Guid</param>
        public static DataTable GetAllQuestions(Guid ListGuid)
        {
            DataTable data = new DataTable();
            data.Columns.Add("title");
            data.Columns.Add("id");
            SPWeb web = SPContext.Current.Web;
            var list = GetSurveyList(web, ListGuid);
            List<string> filter = new List<string>() { "SurveyCycleField", "LableShowField" };
            if (list!=null)
            {
                foreach (SPField item in list.Fields)
                {                    
                    if (item.CanBeDeleted && !filter.Contains(item.TypeAsString))
                    {
                        var dr = data.NewRow();
                        dr["title"] = item.Title;
                        dr["id"] = item.Id;
                        data.Rows.Add(dr);
                    }
                }
            }
            return data;
        }

        /// <summary>
        /// 获取问题的子项
        /// </summary>
        /// <param name="Question"></param>
        public static DataTable GetAllItemByQuestion(Guid ListGuid, string strDisplayName)
        {
            DataTable data = new DataTable();
            data.Columns.Add("item");
            data.Columns.Add("type");
            data.Columns.Add("count",typeof(Int32));
            data.Columns.Add("percent",typeof(Decimal));
            data.Columns.Add("sum",typeof(Int32));

            SPWeb web = SPContext.Current.Web;
            var list = GetSurveyList(web, ListGuid);
            if (list != null)
            {
                SPField item = list.Fields.GetField(strDisplayName);
                switch (item.Type)
                {
                    case SPFieldType.Choice:
                        SPFieldMultiChoice choiceField = (SPFieldMultiChoice)item;
                        foreach (string choiceName in choiceField.Choices)
                        {
                            var dr = data.NewRow();
                            dr["item"] = choiceName;
                            dr["type"] = item.Type.ToString();
                            dr["count"] = 0;
                            dr["percent"] = 0;
                            dr["sum"] = 0;
                            data.Rows.Add(dr);
                        }
                        break;
                    case SPFieldType.MultiChoice:
                        SPFieldMultiChoice MchoiceField = (SPFieldMultiChoice)item;
                        foreach (string choiceName in MchoiceField.Choices)
                        {
                            var dr = data.NewRow();
                            dr["item"] = choiceName;
                            dr["type"] = item.Type.ToString();
                            dr["count"] = 0;
                            dr["percent"] = 0;
                            dr["sum"] = 0;
                            data.Rows.Add(dr);
                        }
                        break;                    
                    #region 其他类型暂时不考虑
                    //case SPFieldType.Text:
                    //    break;
                    //case SPFieldType.AllDayEvent:
                    //    break;
                    //case SPFieldType.Attachments:
                    //    break;
                    //case SPFieldType.Boolean:
                    //    break;
                    //case SPFieldType.Calculated:
                    //    break;                    
                    //case SPFieldType.Computed:
                    //    break;
                    //case SPFieldType.ContentTypeId:
                    //    break;
                    //case SPFieldType.Counter:
                    //    break;
                    //case SPFieldType.CrossProjectLink:
                    //    break;
                    //case SPFieldType.Currency:
                    //    break;
                    //case SPFieldType.DateTime:
                    //    break;
                    //case SPFieldType.Error:
                    //    break;
                    //case SPFieldType.File:
                    //    break;
                    //case SPFieldType.GridChoice:
                    //    break;
                    //case SPFieldType.Guid:
                    //    break;
                    //case SPFieldType.Integer:
                    //    break;
                    //case SPFieldType.Invalid:
                    //    break;
                    //case SPFieldType.Lookup:
                    //    break;
                    //case SPFieldType.MaxItems:
                    //    break;
                    //case SPFieldType.ModStat:
                    //    break;
                    //case SPFieldType.Number:
                    //    break;
                    //case SPFieldType.PageSeparator:
                    //    break;
                    //case SPFieldType.Recurrence:
                    //    break;
                    //case SPFieldType.ThreadIndex:
                    //    break;
                    //case SPFieldType.Threading:
                    //    break;
                    //case SPFieldType.URL:
                    //    break;
                    //case SPFieldType.User:
                    //    break;
                    //case SPFieldType.WorkflowEventType:
                    //    break;
                    //case SPFieldType.WorkflowStatus:
                    //    break;
                    #endregion  
                    default:
                        foreach (SPListItem li in list.Items)
                        {
                            if (li["Author"] != null && li[strDisplayName] != null)
                            {
                                var answer = li[strDisplayName].ToString();
                                answer = answer.NoHtml();
                                if (data.Select("item='" + answer + "'").Count() == 0)
                                {                                    
                                    var dr = data.NewRow();
                                    dr["item"] = answer;
                                    dr["type"] = item.Type.ToString();
                                    dr["count"] = 0;
                                    dr["percent"] = 0;
                                    dr["sum"] = 0;
                                    data.Rows.Add(dr);
                                }                                
                            }
                        }
                        break;
                }
            }
            return data;
        }

    }
}
